<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    width="50%"
    top="5vh"
  >
    <el-form
      ref="createOrEditVehicleForm"
      v-loading="loading"
      label-position="right"
      label-width="140px"
      :model="form"
      :rules="formRules"
    >

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'VehicleNumber\']')" prop="number">
            <el-input v-model="form.number" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'VehicleVIN\']')" prop="vin">
            <el-input v-model="form.vin" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'VehicleLicensePlateNumber\']')" prop="licensePlateNumber">
            <el-input v-model="form.licensePlateNumber" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'Display:Partner\']')" prop="partner">
            <el-input v-model="form.partner" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'Display:VehicleType\']')" prop="vehicleType">
            <el-input v-model="form.vehicleType" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'Display:VehicleYear\']')" prop="vehicleYear">
            <el-date-picker v-model="form.vehicleYear" type="year" value-format="yyyy-MM-dd" format="yyyy" :placeholder="$t('BookStore2[\'Display:VehicleYear\']')" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'Display:PurchasingDate\']')" prop="purchasingDate">
            <el-date-picker v-model="form.purchasingDate" type="date" value-format="yyyy-MM-dd" :placeholder="$t('BookStore2[\'Display:VehicleYear\']')" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'Display:CostAmount\']')" prop="costAmount">
            <el-input v-model="form.costAmount" type="number">
              <template slot="append">CAD</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'VehicleBrand\']')" prop="brand">
            <el-select v-model="form.brand" filterable :placeholder="$t('BookStore2[\'SelectVehicleBrand\']')">
              <el-option v-for="item in dataDict.VehicleBrand" :key="item.key" :label="$t('BookStore2[\'' + item.key + '\']')" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('BookStore2[\'VehicleTireType\']')" prop="tireType">
            <el-radio-group v-model="form.tireType">
              <el-radio v-for="item in dataDict.VehicleTireType" :key="item.key" :label="item.key">{{ $t('BookStore2[\'' + item.key + '\']') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="$t('BookStore2[\'Display:Cost\']')" prop="cost">
        <el-input v-model="form.cost" type="textarea" />
      </el-form-item>
      <el-form-item :label="$t('BookStore2[\'Display:Remark\']')" prop="remark">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
      <el-form-item :label="$t('BookStore2[\'Display:AttachFiles\']')" prop="attachFiles">
        <attach-file-upload ref="upload" :attach-files="form.attachFiles" />
      </el-form-item>
      <el-form-item :label="$t('BookStore2[\'NumberPlates\']')" prop="numberPlates">
        <single-file-upload ref="numberPlates" :attach-file="form.numberPlates" />
      </el-form-item>
      <!-- 隐藏表单 -->
      <el-form-item prop="id" hidden>
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item prop="concurrencyStamp" hidden>
        <el-input v-model="form.concurrencyStamp" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('BookStore2[\'Cancel\']') }}</el-button>
      <el-button type="primary" @click="submitForm">
        <i class="el-icon-check" />
        {{ $t('BookStore2[\'Save\']') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getById,
  create,
  edit
} from '@/api/vehicle/vehicle'
import { getDataDict } from '@/api/data-dict/data-dict'
import AttachFileUpload from '@/views/components/attach-file-upload'
import SingleFileUpload from '@/views/components/single-file-upload'

export default {
  name: 'CreateOrEditVehicle',
  components: { AttachFileUpload, SingleFileUpload },
  props: {
    context: {
      type: Object,
      required: true
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      title: '',
      actionMode: '',
      loading: false,
      dataDict: {},
      form: {
        id: '',
        number: '',
        vin: '',
        licensePlateNumber: '',
        brand: '',
        tireType: 'Enum:VehicleTireType.FourSeasons',
        partner: '',
        vehicleType: '',
        vehicleYear: null,
        purchasingDate: null,
        isMaintaining: false,
        costAmount: 0,
        cost: '',
        remark: '',
        concurrencyStamp: '',
        attachFiles: [],
        numberPlates: {}
      },
      formRules: {
        number: [{ required: true, message: this.$t('BookStore2[\'ThisFieldIsRequired\']'), trigger: 'blur' }],
        vin: [{ required: true, message: this.$t('BookStore2[\'ThisFieldIsRequired\']'), trigger: 'blur' }],
        licensePlateNumber: [{ required: true, message: this.$t('BookStore2[\'ThisFieldIsRequired\']'), trigger: 'blur' }],
        brand: [{ required: true, message: this.$t('BookStore2[\'ThisFieldIsRequired\']'), trigger: 'blur' }],
        tireType: [{ required: true, message: this.$t('BookStore2[\'ThisFieldIsRequired\']'), trigger: 'blur' }]
      }
    }
  },
  watch: {
    context(newVal, oldVal) {
      this.loading = true
      this.title = newVal.title
      this.actionMode = newVal.actionMode
      this.$nextTick(function() {
        if (this.actionMode === 'edit') {
          /* 编辑模式 */
          if (newVal.id) {
            getById(newVal.id).then(resp => {
              const vehicle = resp
              if (vehicle) {
                this.form.id = vehicle.id
                this.form.number = vehicle.number
                this.form.vin = vehicle.vin
                this.form.licensePlateNumber = vehicle.licensePlateNumber
                this.form.brand = vehicle.brand
                this.form.tireType = vehicle.tireType
                this.form.vehicleType = vehicle.vehicleType
                this.form.partner = vehicle.partner
                this.form.vehicleYear = vehicle.vehicleYear
                this.form.purchasingDate = vehicle.purchasingDate
                this.form.cost = vehicle.cost
                this.form.costAmount = vehicle.costAmount
                this.form.remark = vehicle.remark
                this.form.attachFiles = vehicle.attachFiles
                this.form.numberPlates = vehicle.numberPlates || {}
                this.form.concurrencyStamp = vehicle.concurrencyStamp
              }
              this.loading = false
            })
          }
        } else {
          /* 创建模式 */
          this.form.numberPlates = {}
          this.loading = false
        }
      })
    }
  },
  async created() {
    this.dataDict = await getDataDict(['VehicleBrand', 'VehicleTireType'])
  },
  methods: {
    submitForm() {
      this.$refs.createOrEditVehicleForm.validate(async(isValid, invalidFields) => {
        if (isValid) {
          this.form.attachFiles = this.$refs.upload.getAttachFiles()
          if (this.actionMode === 'edit') {
            await edit(this.form.id, this.form)
          } else {
            await create(this.form)
          }
          this.$message({ message: this.$t('BookStore2[\'Ok\']'), type: 'success' })
          this.closeDialog()
          this.$emit('saveSucceed')
        }
      })
    },
    closeDialog() {
      this.resetDialog() // 重置表单
      this.$emit('update:visible', false)
    },
    resetDialog() {
      this.$refs.createOrEditVehicleForm.resetFields()
    }
  }
}
</script>

<style scoped>
</style>
